package com.softeem.service.impl;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.softeem.domain.ShoppingCar;
import com.softeem.service.IShoppingCarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class ShoppingCarServiceImpl implements IShoppingCarService {

    @Autowired
    StringRedisTemplate redisTemplate;


    public List<ShoppingCar> add(String uId, Map map) throws Exception {

        //uid:客户ID

        //商品ID
        String traId = map.get("traId").toString();

        //商品详情
        ObjectMapper om = new ObjectMapper();
        String json = om.writeValueAsString(map);

        //保存到redis
        redisTemplate.opsForHash().put(uId,traId,json);

        //获取数据
        //String s = redisTemplate.opsForHash().get(uId,1001).toString();
        //删除数据
        //redisTemplate.opsForHash().delete(uid,uId);
        List<ShoppingCar> carList = new ArrayList<>();
        //String carList = "";
        //获取数据加入进list中
        ObjectMapper objectMapper = new ObjectMapper();
        for (int i = 1;i<redisTemplate.opsForHash().keys(uId).size()+1;i++){
            Object o = redisTemplate.opsForHash().get(uId, String.valueOf(i));
            ShoppingCar shoppingCar = objectMapper.readValue(o.toString(), ShoppingCar.class);
            carList.add(shoppingCar);
        }

        return  carList;
    }






}
